import { Card, Typography, Form, Input, Button, Upload, Select, message } from 'antd';
import { InboxOutlined, DownloadOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons';
import { toolAPI } from '../utils/api';
import { useState } from 'react';

const { Title } = Typography;
const { Option } = Select;
const { Dragger } = Upload;

const DocumentConvertPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [convertedFileUrl, setConvertedFileUrl] = useState(null);
  const [convertedFileName, setConvertedFileName] = useState('');
  const [file, setFile] = useState(null);

  // 支持的文件类型和对应的转换目标格式
  const supportedFormats = {
    'docx': ['html', 'txt', 'pdf'],
    'doc': ['html', 'txt', 'pdf'],
    'html': ['txt', 'pdf'],
    'txt': ['pdf', 'docx'],
    'pdf': ['txt', 'docx', 'images']
  };

  // 处理文件上传
  const handleUpload = ({ file: uploadFile }) => {
    setFile(uploadFile);
    
    // 提取文件扩展名
    const fileExtension = uploadFile.name.split('.').pop().toLowerCase();
    
    // 检查是否支持该文件类型
    if (!supportedFormats[fileExtension]) {
      message.error('不支持的文件类型，请上传docx、doc、html或txt格式的文件');
      setFile(null);
      form.setFieldValue('targetFormat', undefined);
      return false;
    }
    
    // 更新目标格式选项
    form.setFieldValue('fileType', fileExtension);
    message.success(`已选择文件: ${uploadFile.name}`);
    return false; // 阻止自动上传
  };

  // 处理目标格式变更
  const handleFormatChange = (format) => {
    form.setFieldValue('targetFormat', format);
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    if (!file) {
      message.error('请先选择一个文件');
      return;
    }

    const targetFormat = values.targetFormat;
    if (!targetFormat) {
      message.error('请选择目标格式');
      return;
    }

    setLoading(true);

    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('targetFormat', targetFormat);

      const response = await toolAPI.convertDocument(formData);

      // 处理响应，创建下载链接
      const blob = new Blob([response.data], {
        type: response.headers['content-type']
      });
      const url = window.URL.createObjectURL(blob);
      
      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let fileName = 'converted_file';
      if (contentDisposition) {
        const matches = /filename="([^"]+)"/.exec(contentDisposition);
        if (matches && matches[1]) {
          fileName = matches[1];
        }
      } else {
        // 如果响应头中没有文件名，则根据原文件名和目标格式生成
        const originalFileName = file.name.substring(0, file.name.lastIndexOf('.'));
        fileName = `${originalFileName}.${targetFormat}`;
      }

      setConvertedFileUrl(url);
      setConvertedFileName(fileName);
      message.success('文件转换成功！');
    } catch (error) {
      console.error('文件转换失败:', error);
      message.error(`转换失败: ${error.response?.data?.error || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 处理下载
  const handleDownload = () => {
    if (convertedFileUrl) {
      const link = document.createElement('a');
      link.href = convertedFileUrl;
      link.download = convertedFileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // 可选：下载后清除URL对象以释放内存
      // window.URL.revokeObjectURL(convertedFileUrl);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setFile(null);
    setConvertedFileUrl(null);
    setConvertedFileName('');
  };

  // 获取可用的目标格式选项
  const getFormatOptions = () => {
    const fileType = form.getFieldValue('fileType');
    if (!fileType || !supportedFormats[fileType]) {
      return [];
    }
    
    // 定义格式显示名称映射
    const formatDisplayNames = {
      'html': 'HTML',
      'txt': 'TXT',
      'pdf': 'PDF',
      'docx': 'DOCX',
      'images': '图片集(ZIP)'
    };
    
    return supportedFormats[fileType].map(format => (
      <Option key={format} value={format}>
        {formatDisplayNames[format] || format.toUpperCase()}
      </Option>
    ));
  };

  return (
    <Card className="tool-page">
      <Title level={2}>文档格式转换</Title>
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        className="form-section"
        initialValues={{ targetFormat: undefined }}
      >
        <Form.Item name="fileType" hidden>
          <Input />
        </Form.Item>
        
        <Form.Item 
          label="上传文件"
          required
          className="form-section"
        >
          <Dragger
            accept=".docx,.doc,.html,.txt,.pdf"
            beforeUpload={handleUpload}
            showUploadList={false}
            disabled={loading}
          >
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽文件到此处上传</p>
            <p className="ant-upload-hint">
              支持的文件格式: DOCX, DOC, HTML, TXT, PDF
            </p>
          </Dragger>
        </Form.Item>

        <Form.Item
          label="目标格式"
          name="targetFormat"
          rules={[{ required: true, message: '请选择目标格式' }]}
          className="form-section"
        >
          <Select 
            placeholder="请选择目标格式"
            onChange={handleFormatChange}
            disabled={!file || loading}
            style={{ width: '100%' }}
          >
            {getFormatOptions()}
          </Select>
        </Form.Item>

        <div className="button-group">
          <Button type="primary" htmlType="submit" loading={loading} icon={<FileTextOutlined />}>
            转换文件
          </Button>
          <Button onClick={handleReset} disabled={loading}>
            重置
          </Button>
        </div>
      </Form>

      {/* 转换结果展示 */}
      {convertedFileUrl && (
        <div className="result-section">
          <Title level={3}>转换结果</Title>
          <Card>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <Typography.Text strong>文件名:</Typography.Text>
                <Typography.Text>{convertedFileName}</Typography.Text>
              </div>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />}
                onClick={handleDownload}
              >
                下载文件
              </Button>
            </div>
          </Card>
        </div>
      )}
    </Card>
  );
};

export default DocumentConvertPage;